from appengine_django.models import BaseModel
from google.appengine.ext import db
from django.contrib.auth.models import get_hexdigest
class Player(BaseModel):
    
    email = db.EmailProperty()
    first_name = db.StringProperty()
    last_name = db.StringProperty()    
    friends = db.ListProperty(db.Key)
    verified = db.BooleanProperty(default=False)
    firsthome = db.BooleanProperty(default=True)
    password = db.StringProperty()
    facebook_id = db.StringProperty()
    
    def __unicode__(self):
        return "%s"%(self.first_name or self.email) 

    def setFirstHome(self,aBoolean):
        self.firsthome = aBoolean
        self.put()

    def set_password(self, raw_password):
        import random
        algo = 'sha1'
        salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
        hsh = get_hexdigest(algo, salt, raw_password)
        self.password = '%s$%s$%s' % (algo, salt, hsh)
        self.put()
                     
    def check_password(self,raw_password):    
        algo, salt, hsh = self.password.split('$')
        return hsh == get_hexdigest(algo, salt, raw_password)
    
    @classmethod    
    def is_valid(cls,password,email):
        pl = Player.all().filter('email =',email).get()
        if not pl:
            return False
        
        return pl.check_password(password) and pl or None
    
    @classmethod
    def create_player(cls,email,first_name,facebook_id=None):
        #create the player or return player
        player = Player.all().filter('email =',email).get()
        if not player:
            player = Player(email=email,first_name=first_name,facebook_id=facebook_id)
            player.put()
        return player
        
    def get_pict(self):
        if self.facebook_id:
            return "http://graph.facebook.com/%s/picture"%self.facebook_id
        
        return "/static/images/oliverc.png"
    